package com.bite.forum.controller;


import com.bite.forum.common.AppConfig;
import com.bite.forum.common.AppResult;
import com.bite.forum.common.ResultCode;
import com.bite.forum.exception.ApplicationException;
import com.bite.forum.model.Article;
import com.bite.forum.model.Board;
import com.bite.forum.model.User;
import com.bite.forum.service.IArticleService;
import com.bite.forum.service.IBoardService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IBoardService boardService;
    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping ("/create")
    public AppResult create(HttpServletRequest request ,
                            @RequestParam("boardId") @NonNull Long boardId,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Board board = boardService.selectByPrimaryKey(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            // 返回响应
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        Article article = new Article();
        article.setTitle(title); // 标题
        article.setContent(content); // 正文
        article.setBoardId(boardId); // 版块Id
        article.setUserId(user.getId()); // 作者Id
        // 调用Service
        articleService.create(article);
        // 响应
        return AppResult.success();
    }

    @GetMapping("/getBoardList")
    public AppResult<List<Article>> getAllByBoardId (@RequestParam(value = "boardId", required = false) Long boardId) {

        List<Article> articles;
        if(boardId == null){
            // 定义返回的集合
             articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllBoardId(boardId);
        }
        if (articles == null) {
            // 如果结合集为空，那么创建上个空集合
            articles = new ArrayList<>();
        }
        // 响应结果
        return AppResult.success(articles);
    }

    @GetMapping("/details")
    public AppResult<Article> details(HttpServletRequest request,
                                      @Param("boardId") @NonNull Long id) throws JsonProcessingException {
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        Article article = articleService.selectDetailArticle(id);

        if(user.getId().equals(article.getUserId()) ) {
            article.setIsOwn(true);
        }
        return AppResult.success(article);
    }

    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request ,
                            @RequestParam("id") @NonNull Long id,
                            @RequestParam("title") @NonNull String title,
                            @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }

        Article article = articleService.selectById(id);

        if(article == null){
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_NOT_EXISTS.getMessage());
        }
        if(article.getDeleteState() == 1 || article.getState() == 1){
           return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        if(user.getId() != article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.modify(id , title , content);

        return AppResult.success(ResultCode.SUCCESS);
    }

    //控制点赞数
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request ,
                            @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }

        if(user.getState() == 1){
            log.warn(ResultCode.FAILED_USER_BANNED.toString());

            throw new ApplicationException(ResultCode.FAILED_USER_BANNED.getMessage());
        }

        articleService.thumbsUpById(id);
        return AppResult.success();
    }
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request ,
                                @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null || user.getState() == 1){
            log.warn(ResultCode.FAILED_NOLOGIN.toString());
            throw new ApplicationException(ResultCode.FAILED_NOLOGIN.getMessage());
        }
        Article article = articleService.selectById(id);

        if(article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(user.getId() != article.getUserId()){
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        articleService.deleteById(id);
        return AppResult.success();
    }

    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request ,
                                                   @RequestParam(value = "userId" , required = false) Long userId){
        if(userId == null){
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }

}













